package com.foldingleaf.framework.web.service;

import com.foldingleaf.common.constant.Constants;
import com.foldingleaf.common.utils.MessageUtils;
import com.foldingleaf.common.utils.SecurityUtils;
import com.foldingleaf.common.utils.ShareCodeUtil;
import com.foldingleaf.common.utils.uuid.UUID;
import com.foldingleaf.framework.manager.AsyncManager;
import com.foldingleaf.framework.manager.factory.AsyncFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.foldingleaf.common.core.domain.entity.SysUser;
import com.foldingleaf.common.core.domain.model.LoginUser;
import com.foldingleaf.common.enums.UserStatus;
import com.foldingleaf.common.exception.ServiceException;
import com.foldingleaf.common.utils.StringUtils;
import com.foldingleaf.system.service.ISysUserService;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysUser user = userService.selectUserByUserName(username);
        System.out.println("user:"+user);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            SysUser sysUser = new SysUser();
            sysUser.setUserName(username);
            String substring = username.substring(username.length() - 7);
            String w = username.substring(username.length() - 4);
            sysUser.setPassword(SecurityUtils.encryptPassword(substring));
            sysUser.setSex("0");
            sysUser.setPhonenumber(username);
            sysUser.setNickName("Folding"+ w);
              sysUser.setStatus(UserStatus.OK.getCode());   //设置用户状态为正常
            sysUser.setHashId("0x"+UUID.randomUUID().toString(true));
            sysUser.setCreateBy("user");
            //string转int

            sysUser.setInviteCode(ShareCodeUtil.toSerialCode(Long.parseLong(username)));
            sysUser.setRemark("注册用户");

            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag)
            {
                throw new ServiceException("注册用户失败");
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER,
                        MessageUtils.message("user.register.success")));
                user = userService.selectUserByUserName(username);
            }

            log.info("注册新用户 {}", username);



        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
